package com.chainyoung.component_tmtrade.ui.fragment.fiatcurrency;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.chainyoung.common.appcommon.entity.CommonList;
import com.chainyoung.common.base.BaseFragment;
import com.chainyoung.common.common_widget.loadsir.callback.Callback;
import com.chainyoung.common.common_widget.loadsir.core.LoadService;
import com.chainyoung.common.common_widget.loadsir.core.LoadSir;
import com.chainyoung.common.constant.LibConstant;
import com.chainyoung.common.custom_widget.EmptyCallback;
import com.chainyoung.common.custom_widget.LoadingCallback;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.component_tmtrade.R;
import com.chainyoung.component_tmtrade.R2;
import com.chainyoung.component_tmtrade.bean.FiatCoin;
import com.chainyoung.component_tmtrade.bean.FiatTradeListItem;
import com.chainyoung.component_tmtrade.di.component.DaggerTradeFiatCurrencyComponent;
import com.chainyoung.component_tmtrade.di.module.TradeFiatCurrencyModule;
import com.chainyoung.component_tmtrade.ui.adapter.TradeAgencyAdapter;
import com.chainyoung.component_tmtrade.ui.adapter.TradeFiatCurrencyBuyAdapter;
import com.chainyoung.component_tmtrade.ui.mvp.contract.TradeFiatCurrencyBuyContract;
import com.chainyoung.component_tmtrade.ui.mvp.presenter.TradeFiatCurrencyBuyPresenter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import org.simple.eventbus.Subscriber;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

import static com.chainyoung.component_tmtrade.ui.fragment.fiatcurrency.TradeFiatCurrencyMainFragment.TYPE_BUY;


public class TradeFiatCurrencyTradeFragment extends BaseFragment<TradeFiatCurrencyBuyPresenter> implements TradeFiatCurrencyBuyContract.View {


    @BindView(R2.id.cb_online)
    TextView cbOnline;
    @BindView(R2.id.rv_list)
    RecyclerView rvList;
    @BindView(R2.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R2.id.txt_bit_amount)
    TextView txtBitAmount;

    private boolean isFirst = true;
    private int type = TYPE_BUY;

    private boolean isCanloadMore;
    private int pageNo = 1;
    private boolean isUserOnline = true;

    private List<FiatTradeListItem> mData = new ArrayList<>();
    private TradeFiatCurrencyBuyAdapter mAdapter;
    private String coinName;


    public static TradeFiatCurrencyTradeFragment newInstance(int type) {
        TradeFiatCurrencyTradeFragment fragment = new TradeFiatCurrencyTradeFragment();
        Bundle args = new Bundle();
        args.putInt("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() != null) {
            type = getArguments().getInt("type");
        }
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerTradeFiatCurrencyComponent.builder()
                .appComponent(appComponent)
                .tradeFiatCurrencyModule(new TradeFiatCurrencyModule(this))
                .build()
                .inject(this);
    }


    @Override
    protected void initData() {

    }


    @Override
    protected void initUi() {
        super.initUi();
        coinName = getString(R.string.tmtrade_fiat_currency);
        mAdapter = new TradeFiatCurrencyBuyAdapter(mData, type,coinName);
        rvList.setAdapter(mAdapter);
        rvList.setLayoutManager(new LinearLayoutManager(mContext));
        DividerItemDecoration itemDecoration = new DividerItemDecoration(mContext, DividerItemDecoration.VERTICAL);
        itemDecoration.setDrawable(ContextCompat.getDrawable(mContext, R.drawable.shape_divider_gray_10));
        rvList.addItemDecoration(itemDecoration);

        mAdapter.notifyDataSetChanged();

//        cbOnline.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//            @Override
//            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                isUserOnline = isChecked;
//                pageNo = 1;
//                loadData();
//            }
//        });

        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isCanloadMore) {
                    pageNo++;
                    loadData();
                } else {
                    refreshLayout.finishLoadMore();
                }
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNo = 1;
                loadData();
            }
        });

    }

    @Override
    protected boolean useLoadSir() {
        return true;
    }

    @Override
    protected void onPageRetry(View v) {
        super.onPageRetry(v);
        showPageLoading();
        pageNo = 1;
        loadData();
    }

    @Override
    protected void onFirstUserVisible() {
        if (isFirst) {
            pageNo = 1;
            loadData();
        }
    }


    @Override
    public void onGetFiatTradeListSuccess(CommonList<FiatTradeListItem> data) {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        if (data == null) {
            isCanloadMore = false;
            refreshLayout.setEnableLoadMore(false);
            showPageEmpty();
            return;
        }
        if (data.getList() != null) {
            if (pageNo == 1) {
                mData.clear();
            }
            mData.addAll(data.getList());
        }
        if (data.getList().size() < LibConstant.PAGE_SIZ) {
            isCanloadMore = false;
            refreshLayout.setEnableLoadMore(false);
        } else {
            isCanloadMore = true;
            refreshLayout.setEnableLoadMore(true);
        }
        if (mData.isEmpty()) {
            showPageEmpty();
        } else {
            showPageContent();
        }
        mAdapter.notifyDataSetChanged();

    }

    @Override
    public void onGetFiatTradeListFailed() {
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadMore();
        showPageError();
    }


    @Override
    public void onUserVisible() {
        super.onUserVisible();
        isFirst = false;
        pageNo = 1;
        loadData();
    }

    private void loadData() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("type", type);
        map.put("page", pageNo);
        map.put("limit", LibConstant.PAGE_SIZ);
        //  map.put("user_online", isUserOnline?1:2);
        map.put("coin", coinName.toLowerCase());
        mPresenter.getFiatTradeList(map);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmtrade_fragment_trade_bit;
    }


    @Subscriber
    void onRefreshCoinName(BaseEvent event) {
        if (event.getCode().equals(BaseEvent.EventCode.REFRESH_FIAT_COIN_NAME)) {
            FiatCoin fiatCoin = (FiatCoin) event.getData();
            coinName=fiatCoin.getKey();
            txtBitAmount.setText("数量(" + fiatCoin.getKey().toUpperCase() + ")");
            mAdapter.setCoinName(coinName);
            if (getUserVisibleHint()) {
                pageNo = 1;
                loadData();
            }
        }
    }

}
